<?php

namespace App\Console\Commands;

use App\Http\Model\Rebate;
use App\Http\Model\System;
use App\Http\Model\User;
use App\Http\Services\ApiServices;
use App\Lib\Search;
use Carbon\Carbon;
use DateInterval;
use DatePeriod;
use DateTime;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class CommandCreateDDlog extends Command
{
    protected $signature = 'CommandCreateDDlog';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '创建dd返利数据';


    protected $sysModel;
    protected $userModel;
    protected $rebateModel;
    protected $userTable = 'user';
    protected $finance_wallet_table = 'finance_wallet';

     /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->sysModel = new System();
        $this->userModel = new User();
        $this->rebateModel = new Rebate();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        do{
            //查询后台配置用户
            $sysConfig = $this->sysModel->get_config();
            $openStatus = isset($sysConfig['dd_rebate_button']) ? $sysConfig['dd_rebate_button']['value'] : 0;
            $rebateConfig = isset($sysConfig['dd_rebate_config']) ? json_decode($sysConfig['dd_rebate_config']['value'],true) : [];
            if(empty($openStatus) || empty($rebateConfig)){
                break;
            }
            //查看执行时间是否在获得范围内
            $now = Carbon::now()->toDateTimeString();
            if($now<$rebateConfig['start_time']){
                break;
            }
            //判断时间是否在活动范围内
            $endWeekAddOneDay = Carbon::parse($rebateConfig['end_time'])->addDay(1)->toDateTimeString();//结束后一天
            if($now>$endWeekAddOneDay){
                break;
            }
            //每周一凌晨执行
            $date = Carbon::createFromFormat('Y-m-d', Carbon::today()->toDateString());
            //方法判断是否是周一
            $isMonday = $date->isMonday();
            if(!$isMonday){
                break;
            }
            $lastWeekStart = Carbon::now()->subWeek()->startOfWeek()->toDateString();//上周开始
            $lastWeekEnd = Carbon::now()->subWeek()->endOfWeek()->toDateString();//上周结束

            $nowCount = 0;
            $ddLevel = $rebateConfig['ddLevel'];//DD值门槛
            $ddRate = $rebateConfig['ddRate'];//DD值钻石反比百分


            //活动开始时间/结束时间
            $start = $rebateConfig['start_time'];
            $end = $rebateConfig['end_time'];
            $dateCount = $this->getStartAndEndTimeByDate($start, $end);
            if(isset($dateCount[$lastWeekStart]) && $lastWeekStart < $end){
                $nowCount = $dateCount[$lastWeekStart]['count'];
            }

            if(empty($nowCount)){
                break;
            }
            $rebateUserLists = DB::table($this->userTable.' as u')
                                ->leftJoin($this->finance_wallet_table.' as w','w.user_id','=','u.user_id')
                                ->where('w.wealth_balance','>=', $rebateConfig['wealth_value'])
                                ->get(['u.user_id']);
            $rebateUserLists = objToArray($rebateUserLists);
            if(empty($rebateUserLists)){
                break;
            }
            foreach($rebateUserLists as $user){
                //获取用户上周返利值
                $start = Carbon::now()->subWeek()->startOfWeek()->toDateTimeString();
                $end = Carbon::now()->subWeek()->endOfWeek()->toDateTimeString();
                $allBagValue = $this->rebateModel->getAllBagData($user['user_id'], $start, $end);
                
                $allBagValue = empty($allBagValue['total']) ? 0 : $allBagValue['total'];
                $allColorGiftValue = $this->rebateModel->getAllColorGiftData($user['user_id'], $start, $end);
                $allColorGiftValue = empty($allColorGiftValue['total']) ? 0 : $allColorGiftValue['total'];

                $lastWeekDDvalue = $allBagValue + $allColorGiftValue;
                
                if($lastWeekDDvalue >= $ddLevel){
                    $awardDiamond = intval($lastWeekDDvalue * ($ddRate/100));
                    $insert = [
                        'round_time' => $nowCount,
                        'week' => $lastWeekStart.'-'.$lastWeekEnd,
                        'user_id' => $user['user_id'],
                        'dd_value' => $lastWeekDDvalue,
                        'all_bag_value' => $allBagValue,
                        'all_color_gift_value' => $allColorGiftValue,
                        'award_diamond' => $awardDiamond,
                        'status' => 0,
                        'created_at' => $now,
                    ];
                    $this->rebateModel->insertData($insert);
                }
            }
        }while(false);
        return true;

    }

    /**
     * 根据时间范围获取期数
     */
    public function getStartAndEndTimeByDate($startDate, $endDate)
    {
        $start = new DateTime($startDate);
        $end = new DateTime($endDate);
        $end->modify('next sunday'); // 确保结束日期是下一个周日
        $interval = new DateInterval('P7D'); // 每7天为一周
        $period = new DatePeriod($start, $interval, $end);
    
        $groups = [];
        foreach ($period as $k=>$week) {
            $key = $week->format('Y-m-d'); // 周的起始日期作为数组的键
            $groups[$key] = []; // 初始化该周的数组
        }
        $count = 1;
        for ($current = $start; $current <= $end; $current->modify('+1 day')) {
            $day = $current->format('Y-m-d');
            if (isset($groups[$day])) {
                // 当前日期是周的开始日期，将其加入到对应的周数组中
                $groups[$day]['date'] = $current->format('Y-m-d');
                $groups[$day]['count'] = $count;
                $count = $count+1;
            }
        }
    
        return $groups;
    }
}